var ctx=window.daijia.ctx;
var address=window.daijia.address;
var iserrand=window.daijia.iserrand;
var ismainCompany=window.daijia.mainCompany;
var zhuanxianMap=null;
var driving=null;
var zhuanxian_driving=null;
var driving3=null;
var distance=null;
var timeStr=null;
var startMarkers = null;
var endMarkers = null;
var addressPoint = new Array();
var orderType=null;//订单类型 id
var areaId=null;//类型对应的收费id
var endAdd=null;//目的地是否选填
var price=null;//价格
var baochePrice=null;//包车价格
var jihuoPrice=null;//寄货价格
var currentType=null//当前订单类型
var lastEndAddress = "";
var lastStartAddress = "";
var addmoreFlag = false ;
function initializeMap(){
	var myGeo = new BMap.Geocoder();
	 var point=new BMap.Point(window.daijia.lng,window.daijia.lat);
		if (point) {
			zhuanxianMap = new BMap.Map("zhuanxian_allmap"); 
			zhuanxianMap.centerAndZoom(point, 13);
			zhuanxianMap.enableScrollWheelZoom();
			zhuanxianMap.addEventListener("tilesloaded",function(){
				$(".anchorBL").remove();
			});
			//BMAP_DRIVING_POLICY_LEAST_TIME：最少时间，默认
			//BMAP_DRIVING_POLICY_LEAST_DISTANCE：最短距离
			//BMAP_DRIVING_POLICY_AVOID_HIGHWAYS：避开高速
			driving = new BMap.DrivingRoute(zhuanxianMap, {
				policy : BMAP_DRIVING_POLICY_LEAST_DISTANCE,
				onSearchComplete: function(results){   
					if (driving.getStatus() == BMAP_STATUS_SUCCESS){ 
					 // 获取第一条方案   
						//zhuanxianMap.clearOverlays();
					 var plan = results.getPlan(0); 
					 distance=plan.getDistance();
					 timeStr=plan.getDuration(); 
					 getOrderType();
					 getBudgetedExpensePrice();
					}
				},
				renderOptions: {    //显示到地图上
					map: zhuanxianMap,    
					autoViewport: true 
				}  
			});
			 
		    //右键菜单
		    var contextMenu = new BMap.ContextMenu();    
			var txtMenuItem = [{
				text:'设为预约地',
				callback:function(p){
					//zhuanxianMap.clearOverlays();清除所有覆盖物				   		
	    			var gc = new BMap.Geocoder();
				    gc.getLocation(p, function(rs){
				    	console.debug(rs.addressComponents.city);
				    	if($("#lineId").find("option:selected").attr("startcity").indexOf(rs.addressComponents.city)==-1){
				    		return;
				    	}
				    	var startIcon = new BMap.Icon(ctx+"/assets/img/start.png", new BMap.Size(32,33));
				   		var memberMarker = new BMap.Marker(p,{icon:startIcon});  // 创建标注
				   		zhuanxianMap.removeOverlay(startMarkers);
					    startMarkers=memberMarker;
				   		zhuanxianMap.addOverlay(memberMarker);
				        var addComp = rs.addressComponents;
				        $("#zhuanxianStartAddress").val(addComp.street);
				        $("#zhuanxian_startLat").val(p.lat);
						$("#zhuanxian_startLng").val(p.lng);
						 var tempp=[p];
						    if(endMarkers!=null){
						    	zhuanxianMap.clearOverlays();
						    	driving.search(p, endMarkers.getPosition());
						    	getZhuanxianEmployee();
						    	tempp[tempp.length]=endMarkers.getPosition();
						    }
						    setTimeout(function(){
					            zhuanxianMap.setViewport(tempp); 
					            //调整到最佳视野
					        },100);
				    });
			    }
			},{
			   text:'设为目的地',
			   callback:function(p){
				   var gc = new BMap.Geocoder();
				   gc.getLocation(p, function(rs){
					   if($("#lineId").find("option:selected").attr("endcity").indexOf(rs.addressComponents.city)==-1){
						   var option = $("#lineId").find("option:selected");
						   /*var city = option.attr("endcity")+option.attr("endaddress");
							if(city.trim()!=""){
							zhuanxianMap.centerAndZoom(city,13);
							}
							*/
						   if($("#zhuanxian_endLat").val()=="" || $("#zhuanxian_endLng").val()==""){
							   var city = option.attr("endcity")+option.attr("endaddress");
							   if(city.trim()!=""){
								   zhuanxianMap.centerAndZoom(city,13);
								   focusFlag=true;
							   }
						   }
						   return;
				    	}
					   var startIcon = new BMap.Icon(ctx+"/assets/img/end.png", new BMap.Size(32,33));
					   var memberMarker = new BMap.Marker(p,{icon:startIcon});  // 创建标注
					   zhuanxianMap.removeOverlay(endMarkers);
					    endMarkers=memberMarker;
					   zhuanxianMap.addOverlay(memberMarker);
					   var addComp = rs.addressComponents;
					   $("#zhuanxianEndAddress").val(addComp.street);
					   $("#zhuanxian_endLat").val(p.lat);
					   $("#zhuanxian_endLng").val(p.lng);
					   var tempp=[p];
					    if(startMarkers!=null){
					    	zhuanxianMap.clearOverlays();
					    	driving.search(startMarkers.getPosition(), p);
					    	getZhuanxianEmployee();
					    	tempp[tempp.length]=startMarkers.getPosition();
					    }
					    setTimeout(function(){
				            zhuanxianMap.setViewport(tempp); 
				            //调整到最佳视野
				        },100);
				   });
			   }
			}];
			
			for(var i=0; i < txtMenuItem.length; i++){
				contextMenu.addItem(new BMap.MenuItem(txtMenuItem[i].text,txtMenuItem[i].callback,100));
				if(i==1 || i==3) {
					contextMenu.addSeparator();
				}
			}
			zhuanxianMap.addContextMenu(contextMenu); 
			
			
		}else{
			$.scojs_message("地区"+address+"位置不准确,请重新编辑地区", $.scojs_message.TYPE_ERROR);
		}
	
}

$("#zhuanxian_startTime").change(function(){
	getZhuanxianEmployee();
});
//推荐附近员工
//推荐附近员工
function getZhuanxianEmployee(){
	 if(($("#zhuanxian_startLat").val()!=null&&$("#zhuanxian_startLat").val()!="") && $("#zhuanxian_startLng").val()!=null && $("#zhuanxian_startLng").val()!="" && $("#lineId").val() != null && $("#lineId").val() != "" && $("#zhuanxian_startTime").val()!="" && $("#zhuanxian_startTime").val()!=null){
	   	var islimit=false;
	    $.get(ctx+'/zhuanxian/getEmployees',{
		    	startLat:$("#zhuanxian_startLat").val(),
		    	startLng:$("#zhuanxian_startLng").val(),
		    	lineId:$("#lineId").val(),
		    	orderType:currentType,
		    	peopleNumber:$("#zhuanxian_peopleNumber").val(),
		    	serverTime:$("#zhuanxian_startTime").val(),
		    	},function(data){
		    	$(".zhuanxian_drivers-tr").remove();
				if(data && data.length>0){
					$(data).each(function(i,driver){
						var content="<tr class='zhuanxian_drivers-tr'>"+
									"<td><input type='"+(currentType==1?"checkbox":"radio")+"' name='zhuanxian_checkDriver' value='"+driver.employId+"' /></td>"+
									"<td>"+driver.employName+"</td>"+
									"<td>"+driver.carNumber+"</td>"+
									"<td>"+driver.distance+"</td>"+
									"<tr>";
						$("#zhuanxian_tbodyId").append(content);
					});
				}
			});
	   }else{
		   $(".zhuanxian_drivers-tr").remove();
	   }
}
$(document).ready(function(){

    window.setTimeout(function() {
    	$("#zhuanxian_passengerPhone").change();
    	var zhuanxianstartPoint=new BMap.Point($("#zhuanxian_startLng").val(),$("#zhuanxian_startLat").val());
		var zhuanxianstartIcon = new BMap.Icon(ctx+"/assets/img/start.png", new BMap.Size(32,33));
		startMarkers = new BMap.Marker(zhuanxianstartPoint,{icon:zhuanxianstartIcon});  // 创建标注
	//	 zhuanxianMap.addOverlay(startMarkers);
		var zhuanxianendPoint=new BMap.Point($("#zhuanxian_endLng").val(),$("#zhuanxian_endLat").val());
		var zhuanxianendIcon = new BMap.Icon(ctx+"/assets/img/end.png", new BMap.Size(32,33));
		 endMarkers = new BMap.Marker(zhuanxianendPoint,{icon:zhuanxianendIcon});  // 创建标注
		 zhuanxianMap.addOverlay(endMarkers);
		 zhuanxianMap.addOverlay(startMarkers);
		 getZhuanxianEmployee();
		 zhuanxianMap.clearOverlays();
		 driving.search(zhuanxianstartPoint, zhuanxianendPoint);
	
		 setTimeout(function(){
			 
	            zhuanxianMap.setViewport([zhuanxianstartPoint,zhuanxianendPoint]); 
	            //调整到最佳视野
	        },100);
    }, 100)
	getPrice();
	$("#zhuanxian_startTime").val(new Date(new Date().getTime()+1000*60*3).Format("yyyy-MM-dd hh:mm"))
	$("#zhuanxian_startTime").datetimepicker({format: 'yyyy-mm-dd HH:ii', language: 'zh-CN', minView: 'hour', pickDate: true, pickTime: false, inputMask: false, autoclose: true ,startDate:new Date() });
	initializeMap();
		//公司修改后对应的车辆类型也修改
		$("#zhuanxian_companyId").change(function(){
	    	var companyId=$("#zhuanxian_companyId").val();
	    	$.get(ctx+'/zhuanxian/queryLines',{'companyId':companyId},function(data){
	    		if(data.success){
					console.log("test222");
	    			$("#lineId").html("");
	    			if(data.lines==null||data.lines.length==0){
	    				$("#lineId").append("<option value=''>该公司暂未设置线路</option>");
	    			}
	    			$(data.lines).each(function(index,line){
						var id=line.id;
						var lineName=line.name;
						var company_name="";
						if(data.company_main){
							company_name="&emsp;&emsp;&emsp;&emsp;"+line.companyName;
						}
		            	var text="<option value="+id+" "+((zhuanxian_lineId==id)?"selected='selected'":"")+" jihuoareaid='"+line.jihuoAreaId+"' baocheareaid='"+line.baocheAreaId+"' pingcheareaid='"+line.areaId+"'  startcity='"+line.startCity+"' startaddress='"+line.startAddress+"' endcity='"+line.endCity+"' endaddress='"+line.endAddress+"'>"+lineName+company_name+"</option>";
		            	$("#lineId").append(text);
					 });
	    			
	    			if($("#lineId").val()!="" && $("#lineId").val()!=null && typeof($("#lineId").val())!=undefined){
	    				getPrice();
	    			}else{
	    				$("#zhuanxian_budgetPay").val("");
	    			}
	    			
	    			if((zhuanxian_lineId!=$("#lineId").val())){
	    				$("#lineId").change();
	    			}
	    			
	    			getZhuanxianEmployee();
	    		}
	    	},'json');
		});
		$("#zhuanxian_passengerPhone").change(function(){
			$.get(ctx+'/member/findByPhone',{'phone':$(this).val(),'couponType':'zhuanxian'},function(data){
				if(data.passenger!=null){
					$("#zhuanxian_passengerId").val(data.passenger.id);
					$("#zhuanxian_passengerName").val(data.passenger.name);
					$("#zhuanxian_passengerPhone").val(data.passenger.phone);
					$("#zhuanxian_clientVirtual").text(data.passenger.drawMoney+data.passenger.nodrawMoney+"元");
					if(data.passenger.inBlackList){
						$("#zhuanxian_membertype").html("黑名单");
					}else{
						$("#zhuanxian_membertype").html(data.passenger.typeStr);
					}
					if(ismainCompany=="true"){
						$("#zhuanxian_companyId option").each(function(index,element){
							if($(element).attr("value")==data.passenger.companyId){
								$(element).attr("selected","selected");
								return false;
							}
						});
					}
					var companyId=data.passenger.companyId;
					$("#zhuanxian_companyId").change();
			    	if(data.coupons!=null&&data.coupons.length>0){
						var text="<option value=''>"+"请选择优惠券"+"</option>";
						for(var i=0;i<data.coupons.length;i++){
							text+= "<option value='"+data.coupons[i].id+"'>"+data.coupons[i].couponRule.title+"</option>";
						}
						$("#zhuanxian_couponId").empty();
						if(text!=""){
							$("#zhuanxiancouponInput").css("display","block");
							$("#zhuanxian_couponId").append(text);
						}
						
					}else{
						$("#zhuanxiancouponInput").css("display","none");
						$("#zhuanxian_couponId").empty();
					}
				}else{
					$("#zhuanxiancouponInput").css("display","none");
					$("#zhuanxian_couponId").empty();
					$("#zhuanxian_passengerId").val("");
					$("#zhuanxian_passengerName").val("先生/女士");
					$("#zhuanxian_membertype").html("新客户");
					$("#zhuanxian_clientVirtual").html("0元");
				}
			});
			
		});
		$("#lineId").change(function(){
			 var option = $(this).find("option:selected");
			var city = option.attr("startcity")+option.attr("startaddress");
			if(city.trim()!=""){
				zhuanxianMap.centerAndZoom(city,13); 
			}
			$("#zhuanxianEndAddress").val("");
			$("#zhuanxian_endLat").val("");
			$("#zhuanxian_endLng").val("");
			$("#zhuanxianStartAddress").val("");
			$("#zhuanxian_startLat").val("");
			$("#zhuanxian_startLng").val("");
			startMarkers = null;
		    endMarkers = null;
		    zhuanxianMap.clearOverlays();
			getPrice();
			getZhuanxianEmployee();
		});
		var focusFlag = true;
		$("#zhuanxianEndAddress").focus(function(){
			 var option = $("#lineId").find("option:selected");
			 /*var city = option.attr("endcity")+option.attr("endaddress");
				if(city.trim()!=""){
					zhuanxianMap.centerAndZoom(city,13); 
				}
			 */
			 if($("#zhuanxian_endLat").val()=="" || $("#zhuanxian_endLng").val()==""){
			
				   var city = option.attr("endcity")+option.attr("endaddress");
				   if(city.trim()!=""){
					   zhuanxianMap.centerAndZoom(city,13); 
						focusFlag=true;
					}
			 }else{
				 var p = new BMap.Point(parseFloat($("#zhuanxian_endLng").val()),parseFloat($("#zhuanxian_endLat").val()));
				 zhuanxianMap.centerAndZoom(p, 13);
				 
			 }	 
			
		});
		$("#zhuanxianStartAddress").focus(function(){
			var option = $("#lineId").find("option:selected");
			/*var city = option.attr("startcity")+option.attr("startaddress");
			if(city.trim()!=""){
				zhuanxianMap.centerAndZoom(city,13); 
			}*/
			if($("#zhuanxian_startLat").val()=="" || $("#zhuanxian_startLng").val()==""){
			
					var city = option.attr("startcity")+option.attr("startaddress");
					if(city.trim()!=""){
						zhuanxianMap.centerAndZoom(city,13); 
					} 
					focusFlag=false;
			}else{
				 var p = new BMap.Point(parseFloat($("#zhuanxian_startLng").val()),parseFloat($("#zhuanxian_startLat").val()));
				 zhuanxianMap.centerAndZoom(p, 13);
			}
		});
		$("#zhuanxian_peopleNumber").change(function(){
			if(typeof(price) != undefined && price  != null){
				$("#zhuanxian_budgetPay").val(parseInt($(this).val())*price);
			}
			getZhuanxianEmployee();
			getBudgetedExpensePrice();
		});
	
		$("#zhuanxian_saveOrder").click(function(){
			if(addmoreFlag){
				return;
			}
			getOrderType();
			if(currentType==null|| typeof(currentType) == undefined){
				$.scojs_message("请选择订单类型", $.scojs_message.TYPE_ERROR);
				return;
			}
			if($("#zhuanxian_passengerPhone").val()==''){
				$.scojs_message("请填写客户电话", $.scojs_message.TYPE_ERROR);
				return;
			}
			if(ismainCompany=="true" && !$("#companyId3").val()){
				$.scojs_message("请选择公司", $.scojs_message.TYPE_ERROR);
				return;
			}
			if($("#zhuanxian_startTime").val()==''){
				$.scojs_message("请填写预约时间", $.scojs_message.TYPE_ERROR);
				return;
			}else if(!/^(\d{4})\-(\d{2})\-(\d{2}) (\d{2}):(\d{2})$/.test($("#zhuanxian_startTime").val())){
				$.scojs_message("时间格式不正确,如"+new Date().Format("yyyy-MM-dd hh:ss"), $.scojs_message.TYPE_ERROR);
				return;
			}else{
				if(new Date($("#zhuanxian_startTime").val().replace("-","/")).getTime()<new Date().getTime()){
					$.scojs_message("预约时间请大于当前时间", $.scojs_message.TYPE_ERROR);
					return;
				}
			}
			if($("#lineId").val()==''){
				$.scojs_message("请选择线路", $.scojs_message.TYPE_ERROR);
				return;
			}
			if(($("#zhuanxian_peopleNumber").val()==''&&currentType==0) || $("#zhuanxian_peopleNumber").val()>99){
				$.scojs_message($("#zhuanxian_peopleNumber").val()>99?"乘坐人数不能大于99位":"请填写乘坐人数", $.scojs_message.TYPE_ERROR);
				return;
			}
			if(($("#zhuanxian_peopleNumber").val()==''&&currentType==1) || $("#zhuanxian_peopleNumber").val()>99){
				$.scojs_message($("#zhuanxian_peopleNumber").val()>99?"包车车辆不能大于99辆":"请填写包车车辆", $.scojs_message.TYPE_ERROR);
				return;
			}
			if(($("#zhuanxian_takeDeliveryName").val()==''&&currentType==2 ) || ($("#zhuanxian_takeDeliveryPhone").val()==''&&currentType==2)){
				$.scojs_message("请填写收货人信息", $.scojs_message.TYPE_ERROR);
				return;
			}
			if($("#zhuanxianStartAddress").val()==''){
				$.scojs_message("请填写预约地", $.scojs_message.TYPE_ERROR);
				return;
			}
			if($("#zhuanxian_startLat").val()==null || $("#zhuanxian_startLng").val()==null){
				$.scojs_message("请先定位你的预约地", $.scojs_message.TYPE_ERROR);
				return false;
			}
			if($("#zhuanxianEndAddress").val()==''){
				$.scojs_message("请填写目的地", $.scojs_message.TYPE_ERROR);
				return;
			}
			if($("#zhuanxian_endLat").val()==null || $("#zhuanxian_endLng").val()==null){
				$.scojs_message("请先定位你的目的地", $.scojs_message.TYPE_ERROR);
				return false;
			}
			 if(currentType==1&&($("input[name=zhuanxian_checkDriver]:checked").length)>$("#zhuanxian_peopleNumber").val()){
	            	$.scojs_message("选择服务人员数量不能超过所需车辆数", $.scojs_message.TYPE_ERROR);
					return false;
	            }		
			var zhuanxianemployId="";
			var zhuanxianemployArr=[];
			$("input[name=zhuanxian_checkDriver]:checked").each(function(index,element){
				zhuanxianemployArr.push($(element).val());
			});
			if(null!=zhuanxianemployArr && zhuanxianemployArr.length>0){
				zhuanxianemployId=zhuanxianemployArr.join(",");
			}
			addmoreFlag = true;
			if(ismainCompany){
				$.post(ctx+"/zhuanxian/createOrder",
						{
					 orderType:currentType,
					 passengerId:$("#zhuanxian_passengerId").val(),
	            	 passengerName:$("#zhuanxian_passengerName").val(),
	            	 passengerPhone:$("#zhuanxian_passengerPhone").val(),
	            	 companyId:$("#zhuanxian_companyId").val(),
	            	 companyName:$("#zhuanxian_companyId").find("option:selected").text(),
	            	 startTime:$("#zhuanxian_startTime").val(),
	            	 lineId:$("#lineId").val(),
	            	 peopleNumber:currentType!=2?$("#zhuanxian_peopleNumber").val():"",
	            	 startAddress:$("#zhuanxianStartAddress").val(),
	            	 startLat:$("#zhuanxian_startLat").val(),
	            	 startLng:$("#zhuanxian_startLng").val(),
	            	 endAddress:$("#zhuanxianEndAddress").val(),
	            	 endLat:$("#zhuanxian_endLat").val(),
	            	 endLng:$("#zhuanxian_endLng").val(),
	            	 couponId:$("#zhuanxian_couponId").val(),
	            	 budgetPay:$("#zhuanxian_budgetPay").val(),
	            	 memo:$("#zhuanxian_orderMemo").val(),
	            	 takeDeliveryName:currentType==2?$("#zhuanxian_takeDeliveryName").val():"",
	            	 takeDeliveryPhone:currentType==2?$("#zhuanxian_takeDeliveryPhone").val():"",
	            	 employId:zhuanxianemployId
						},function(data){
							
							console.debug(data);
					   if(data.success){
						   $.scojs_message("下单成功", $.scojs_message.TYPE_OK);
		            		 issubmit=true;
		            		 window.close();
		            		 window.opener.location.reload(true);
		            		 
		            	 }else{
		            		 $.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
		            	 }
						addmoreFlag = false;
				}).error(function() {  addmoreFlag=false; });
			}else{
				$.post(ctx+"/zhuanxian/createOrder",
						{
					 orderType:currentType,
					 passengerId:$("#zhuanxian_passengerId").val(),
	            	 passengerName:$("#zhuanxian_passengerName").val(),
	            	 passengerPhone:$("#zhuanxian_passengerPhone").val(),
	            	 startTime:$("#zhuanxian_startTime").val(),
	            	 lineId:$("#lineId").val(),
	            	 peopleNumber:currentType!=2?$("#zhuanxian_peopleNumber").val():"",
	            	 startAddress:$("#zhuanxianStartAddress").val(),
	            	 startLat:$("#zhuanxian_startLat").val(),
	            	 startLng:$("#zhuanxian_startLng").val(),
	            	 endAddress:$("#zhuanxianEndAddress").val(),
	            	 endLat:$("#zhuanxian_endLat").val(),
	            	 endLng:$("#zhuanxian_endLng").val(),
	            	 couponId:$("#zhuanxian_couponId").val(),
	            	 budgetPay:$("#zhuanxian_budgetPay").val(),
	            	 memo:$("#zhuanxian_orderMemo").val(),
	            	 takeDeliveryName:currentType==2?$("#zhuanxian_takeDeliveryName").val():"",
	            	 takeDeliveryPhone:currentType==2?$("#zhuanxian_takeDeliveryPhone").val():"",
	            	 employId:zhuanxianemployId
						},function(data){
							
							console.debug(data);
					   if(data.success){
						   $.scojs_message("下单成功", $.scojs_message.TYPE_OK);
		            		 issubmit=true;
		            		 window.close();
		            		 window.opener.location.reload(true);
		            		 
		            	 }else{
		            		 $.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
		            	 }
						addmoreFlag=false;
				}).error(function() {  addmoreFlag=false; });
			}
			
			
			
		});
		
$("#zhuanxian_orderType li").click(function(){
	currentType = parseInt($(this).attr("val"));
	var type = currentType;
	if(type==0){
		   $("#zhuanxian_peopleNumber").val(1);
		   $("#zhuanxian_peopleNumber_text").text("乘车人数");
		   $("#zhuanxian_peopleNumber_text_addon").text("位");
		   $("#zhuanxian_peopleNumber_div").show();
		   $("#zhuanxian_startTime_text").text("预约时间");
		   if(typeof(price) != undefined && price  != null){
				$("#zhuanxian_budgetPay").val(parseInt($("#zhuanxian_peopleNumber").val())*price);
			}
		   $("#zhuanxianTakeDelivery_div").hide();
	   }else if(type==1){
		   $("#zhuanxian_peopleNumber").val(1);
		   $("#zhuanxian_peopleNumber_text").text("包车车辆");
		   $("#zhuanxian_peopleNumber_text_addon").text("辆");
		   $("#zhuanxian_peopleNumber_div").show();
		   $("#zhuanxian_startTime_text").text("预约时间");
		   if(typeof(baochePrice) != undefined && baochePrice  != null){
				$("#zhuanxian_budgetPay").val(parseInt($("#zhuanxian_peopleNumber").val())*baochePrice);
			}
		   $("#zhuanxianTakeDelivery_div").hide();
	   }else if(type==2){
		   if(typeof(jihuoPrice) != undefined && jihuoPrice  != null){
				$("#zhuanxian_budgetPay").val(jihuoPrice);
			} 
		   $("#zhuanxian_peopleNumber_text").text("乘车人数");
		   $("#zhuanxian_peopleNumber_text_addon").text("位");
		   $("#zhuanxian_peopleNumber").val("");
		   $("#zhuanxian_peopleNumber_div").hide();
		   $("#zhuanxian_startTime_text").text("寄货时间");
		   $("#zhuanxianTakeDelivery_div").show();
	   }
	getBudgetedExpensePrice();
	getZhuanxianEmployee();
});		
$("#zhuanxian_wanghuan").click(function(){
	var startLng = 	$("#zhuanxian_startLng").val();
	var startLat = 	$("#zhuanxian_startLat").val();
	var startAddress = $("#zhuanxianStartAddress").val();
	$("#zhuanxian_startLng").val($("#zhuanxian_endLng").val());
	$("#zhuanxian_startLat").val($("#zhuanxian_endLat").val());
	$("#zhuanxianStartAddress").val($("#zhuanxianEndAddress").val());
	$("#zhuanxian_endLng").val(startLng);
	$("#zhuanxian_endLat").val(startLat);
	$("#zhuanxianEndAddress").val(startAddress);
	var starts = startMarkers;
	startMarkers =  endMarkers;
	endMarkers = starts;
	zhuanxianMap.clearOverlays();
	if(startMarkers!=null && endMarkers!=null){
		driving.search(startMarkers.getPosition(), endMarkers.getPosition());
	}
	getZhuanxianEmployee();
})	
$("#btn-zhuanxianStartAddress").click(function(){
	if($("#zhuanxianStartAddress").val()==''){
		$.scojs_message("请填写预约地", $.scojs_message.TYPE_ERROR);
	}else{
		var local = new BMap.LocalSearch(zhuanxianMap, {
			renderOptions:{map: zhuanxianMap, autoViewport:true}
		});
		
		 var option = $("#lineId").find("option:selected");
		 var city = option.attr("startcity")+option.attr("startaddress");
		 zhuanxianMap.clearOverlays();
		console.debug(city+$("#zhuanxianStartAddress").val());
		local.search(city+$("#zhuanxianStartAddress").val());
		local.setInfoHtmlSetCallback(function(poi,html){
			$("#zhuanxianStartAddress").val(poi.title);
			$("#zhuanxian_startLat").val(poi.marker.point.lat);
			$("#zhuanxian_startLng").val(poi.marker.point.lng);
			var startIcon = new BMap.Icon(ctx+"/assets/img/start.png", new BMap.Size(32,33));
		    var marker = new BMap.Marker(poi.marker.point,{icon:startIcon}); 
			zhuanxianMap.removeOverlay(startMarkers);
		    startMarkers=marker;
		//	zhuanxianMap.addOverlay(marker);
			    var tempp=[poi.marker.point];
			    if(endMarkers!=null){
			    	driving.search(poi.marker.point, endMarkers.getPosition());
			    	tempp[tempp.length]=endMarkers.getPosition();
			    	getZhuanxianEmployee();
			    }
			   /* setTimeout(function(){
		            zhuanxianMap.setViewport(tempp); 
		            //调整到最佳视野
		        },100);*/
		});
	}
});
$("#btn-zhuanxianEndAddress").click(function(){
	if($("#zhuanxianEndAddress").val()==''){
		$.scojs_message("请填写目的地", $.scojs_message.TYPE_ERROR);
	}else{
		var local = new BMap.LocalSearch(zhuanxianMap, {
			renderOptions:{map: zhuanxianMap, autoViewport:true}
		});
		var option = $("#lineId").find("option:selected");
		var city = option.attr("endcity")+option.attr("endaddress");
		zhuanxianMap.clearOverlays();
		local.search(city+$("#zhuanxianEndAddress").val());
		local.setInfoHtmlSetCallback(function(poi,html){
			$("#zhuanxianEndAddress").val(poi.title)
			$("#zhuanxian_endLat").val(poi.marker.point.lat);
			$("#zhuanxian_endLng").val(poi.marker.point.lng);
			var endIcon = new BMap.Icon(ctx+"/assets/img/end.png", new BMap.Size(32,33));
			var marker = new BMap.Marker(poi.marker.point,{icon:endIcon}); 
			zhuanxianMap.removeOverlay(endMarkers);
			endMarkers=marker;
		//	zhuanxianMap.addOverlay(marker);
			var tempp=[poi.marker.point];
			if(startMarkers!=null){
				driving.search(startMarkers.getPosition(), poi.marker.point);
				tempp[tempp.length]=startMarkers.getPosition();
				getZhuanxianEmployee();
			}
			/*setTimeout(function(){
				zhuanxianMap.setViewport(tempp); 
				//调整到最佳视野
			},100);*/
		});
	}
});

			
		
		
		
});
$("#zhuanxianStartAddress").AutoComplete({
	data: ctx+"/zhuanxian/getHistoryInputedPlace",
	ajaxDataType: "json",
	itemHeight: 24,
	ajaxParams:function(keyword){
		 var option = $("#lineId").find("option:selected");
		var city = option.attr("startcity");
		var temp  =  city.split("-");
		 if(temp.length>1){
			 city= temp[1];
		 }else{
			 city = temp[0];
		 }
		return {'city':city};
	},
	max:1,
	width: "auto",
	async: true,
	listStyle: "custom",
	emphasis: false,
	matchHandler: function(keyword, data){
		return true;
	},
	createItemHandler: function(index, data){
		if(data.address.length>14){
			return "<span title='"+data.address+"'>"+data.address.substring(0,14)+"</span>";
		}
		return "<span title='"+data.address+"'>"+data.address+"</span>";
	},
	afterSelectedHandler: function(data){
	//	var address = (data.address).split(" ");
		var gc = new BMap.Geocoder();
		var p = new BMap.Point(data.longitude,data.latitude);
		 gc.getLocation(p, function(rs){
		    	console.debug(rs.addressComponents.city);
		    	if($("#lineId").find("option:selected").attr("startcity").indexOf(rs.addressComponents.city)==-1){
		    		$("#zhuanxianStartAddress").val(lastStartAddress);
		    	}else{
		    		$("#zhuanxianStartAddress").val(data.address);
		    		lastStartAddress = data.address;
		    		$("#zhuanxian_startLat").val(data.latitude);
		    		$("#zhuanxian_startLng").val(data.longitude);
		    		var p = new BMap.Point(data.longitude,data.latitude);
		    		var startIcon = new BMap.Icon(ctx+"/assets/img/start.png", new BMap.Size(32,33));
		    	    var marker = new BMap.Marker(p,{icon:startIcon}); 
		    	    zhuanxianMap.removeOverlay(startMarkers);
		    	    startMarkers=marker;
		    	    zhuanxianMap.addOverlay(marker);
		    	    var tempp=[p];
		    	    if(endMarkers!=null){
		    	    	zhuanxianMap.clearOverlays();
		    	    	driving.search(p, endMarkers.getPosition());
		    	    	getZhuanxianEmployee();
		    	    	tempp[tempp.length]=endMarkers.getPosition();
		    	    }
		    	    setTimeout(function(){
		                zhuanxianMap.setViewport(tempp); 
		                //调整到最佳视野
		            },100);
		    	}
		   });
		
	}
}).AutoComplete('show');

$("#zhuanxianEndAddress").AutoComplete({
	data: ctx+"/zhuanxian/getHistoryInputedPlace",
	ajaxDataType: "json",
	itemHeight: 24,
	ajaxParams:function(keyword){
		 var option = $("#lineId").find("option:selected");
		var city = option.attr("endcity");
		var temp  =  city.split("-");
		 if(temp.length>1){
			 city= temp[1];
		 }else{
			 city = temp[0];
		 }
		return {'city':city};
	},
	max:1,
	width: "auto",
	async: true,
	listStyle: "custom",
	emphasis: false,
	matchHandler: function(keyword, data){
		return true;
	},
	createItemHandler: function(index, data){
		if(data.address.length>14){
			return "<span title='"+data.address+"'>"+data.address.substring(0,14)+"</span>";
		}
		return "<span title='"+data.address+"'>"+data.address+"</span>"; 
	},
	afterSelectedHandler: function(data){
	//	var address = (data.address).split(" ");
		
		var p = new BMap.Point(data.longitude,data.latitude);
		var gc = new BMap.Geocoder();
	    gc.getLocation(p, function(rs){
	    	console.debug(rs.addressComponents.city);
	    	if($("#lineId").find("option:selected").attr("endcity").indexOf(rs.addressComponents.city)==-1){
	    		$("#zhuanxianEndAddress").val(lastEndAddress);
	    	}else{
	    		$("#zhuanxianEndAddress").val(data.address);
	    		lastEndAddress = data.address;
	    		$("#zhuanxian_endLat").val(data.latitude);
	    		$("#zhuanxian_endLng").val(data.longitude); 
	    		var p = new BMap.Point(data.longitude,data.latitude);
	    		var startIcon = new BMap.Icon(ctx+"/assets/img/end.png", new BMap.Size(32,33));
	    	    var marker = new BMap.Marker(p,{icon:startIcon}); 
	    	    zhuanxianMap.removeOverlay(endMarkers);
	    	    endMarkers=marker;
	    	    zhuanxianMap.addOverlay(marker);
	    	    var tempp=[p];
	    	    if(startMarkers!=null){
	    	    	zhuanxianMap.clearOverlays();
	    	    	driving.search(startMarkers.getPosition(), p);
	    	    	getZhuanxianEmployee();
	    	    	tempp[tempp.length]=startMarkers.getPosition();
	    	    }
	    	    setTimeout(function(){
	                zhuanxianMap.setViewport(tempp); 
	                //调整到最佳视野
	            },100);
	    		
	    	}});
		
	}
}).AutoComplete('show');
function getBudgetedExpensePrice(){
	var areaId;
	var type = currentType;
	if(timeStr!=null && distance!=null){
		if(type ==0){
			areaId = $("#lineId").find("option:selected").attr("pingcheareaid");
		}else if(type ==1){
			areaId = $("#lineId").find("option:selected").attr("baocheareaid");
		}else if(type ==2){
			areaId = $("#lineId").find("option:selected").attr("jihuoareaid");
		}
		console.debug($("#lineId"));
		 $.post(ctx+"/zhuanxian/getBudgetedExpensePrice",
				   {areaId:areaId,
				    time:timeStr,
				    mileage:distance},function(data){							    	
				    	$("#shouldPay").val(data.money);
				    	$("#startPrice").val(data.startPrice);
				    	$("#mileagePrice").val(data.mileagePrice);
				    	$("#travelTimePrice").val(data.travelTimePrice);
				    	$("#travelTime").val(data.travelTime);
				    	$("#mileage").val(data.mileage);
				    	$(".mileage_text").text("预计路程:"+data.mileage+"公里");
				    	$(".travelTime_text").text("预计时间:"+data.travelTime+"分钟");
				    	if(getOrderType()!=2){
				    		$("#zhuanxian_budgetPay").val(parseInt($("#zhuanxian_peopleNumber").val()=="" || $("#zhuanxian_peopleNumber").val()==undefined ?1:$("#zhuanxian_peopleNumber").val())*data.money);
				    	}else{
				    		$("#zhuanxian_budgetPay").val(data.money);
				    	}
				    	
				    	
				    },"json");	
	}
	
}
function getPrice(){
	$.post(ctx+"/zhuanxian/getPrice",
			   {lineId:$("#lineId").val()},function(data){							    	
				   price=data.money;
				   baochePrice=data.baocheMoney;
				   jihuoPrice=data.jihuoMoney;
				  
				   var type = getOrderType();
				   if(type==0){
					   if(typeof(price) != undefined && price  != null){
							$("#zhuanxian_budgetPay").val(parseInt($("#zhuanxian_peopleNumber").val())*price);
						}
					   $("#zhuanxian_peopleNumber_text").text("乘车人数");
					   $("#zhuanxian_peopleNumber_text_addon").text("位");
					   $("#zhuanxian_peopleNumber_div").show();
					   $("#zhuanxian_startTime_text").text("预约时间");
				   }else if(type==1){
					   $("#zhuanxian_peopleNumber_text").text("包车车辆");
					   $("#zhuanxian_peopleNumber_text_addon").text("辆");
					   $("#zhuanxian_peopleNumber_div").show();
					   $("#zhuanxian_startTime_text").text("预约时间");
					   if(typeof(baochePrice) != undefined && baochePrice  != null){
							$("#zhuanxian_budgetPay").val(parseInt( $("#zhuanxian_peopleNumber").val())*baochePrice);
						}
				   }else if(type==2){
					   if(typeof(jihuoPrice) != undefined && jihuoPrice  != null){
							$("#zhuanxian_budgetPay").val(jihuoPrice);
						} 
					   $("#zhuanxian_peopleNumber_text").text("乘车人数");
					   $("#zhuanxian_peopleNumber_text_addon").text("位");
					   $("#zhuanxian_peopleNumber").val("");
					   $("#zhuanxian_peopleNumber_div").hide();
					   $("#zhuanxian_startTime_text").text("寄货时间");
					   
				   }
			    },"json");
}
function getOrderType(){
	var type=null;
	var li = $("#zhuanxian_orderType li[class=active]")[0];
	type=$(li).attr("val");
	currentType=type;
	return parseInt(type);
}


Date.prototype.Format = function(fmt) 	
{ 
  var o = { 
    "M+" : this.getMonth()+1,                 //月份 
    "d+" : this.getDate(),                    //日 
    "h+" : this.getHours(),                   //小时 
    "m+" : this.getMinutes(),                 //分 
    "s+" : this.getSeconds(),                 //秒 
    "q+" : Math.floor((this.getMonth()+3)/3), //季度 
    "S"  : this.getMilliseconds()             //毫秒 
  }; 
  if(/(y+)/.test(fmt)) 
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
  for(var k in o) 
    if(new RegExp("("+ k +")").test(fmt)) 
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
  return fmt; 
}
